 package com.gdqy.FCS.web;


import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;


import java.util.Set;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import redis.clients.jedis.Jedis;

import com.gdqy.FCS.common.api.FastResponse;
import com.gdqy.FCS.common.api.ListResponse;
import com.gdqy.FCS.common.api.ObjResponse;
import com.gdqy.FCS.common.mvc.Args;
import com.gdqy.FCS.entity.Dictionary;
import com.gdqy.FCS.entity.DictionaryType;
import com.gdqy.FCS.entity.Fabric;
import com.gdqy.FCS.entity.FabricComponent;
import com.gdqy.FCS.entity.User;
import com.gdqy.FCS.entity.Weave;
import com.gdqy.FCS.service.DesignerInfoService;
import com.gdqy.FCS.service.DictionaryService;
import com.gdqy.FCS.service.DictionaryTypeService;
import com.gdqy.FCS.service.FabricComponentService;
import com.gdqy.FCS.service.FabricService;
import com.gdqy.FCS.service.UserService;
import com.gdqy.FCS.service.WeaveService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;




@Controller
@RequestMapping("test")
public class TestController {
	@Autowired
	private UserService userService;
	@Autowired
	private DesignerInfoService designerInfoService;
	@Autowired
	private DictionaryService dictionaryService;
	
	@Autowired
	private DictionaryTypeService dictionaryTypeService;
	
	@Autowired
	private FabricService fabricService;
	
	@Autowired
	private FabricComponentService fabricComponentService;	
	
	@Autowired
	private WeaveService weaveService;
	
	private Jedis jedis;
	
	private static Logger logger = Logger.getLogger(TestController.class);
	
	
	@RequestMapping("test")
	public ModelAndView test() throws Exception {		
					

		ModelAndView mav = new ModelAndView("login");
		
		return mav;
	}
	
	@RequestMapping("test2")
	public void test1(@Validated User user,BindingResult bindingResult){
		if(bindingResult.hasErrors()){
			List<ObjectError> allErrors = bindingResult.getAllErrors();
			for(ObjectError objectError:allErrors){
				System.out.println(objectError.getCode());
				System.out.println(objectError.getDefaultMessage());
			}

		}
	}
	
	/*
	 * 
	 * 返回json数据
	 * 
	 * */
	@RequestMapping("/test3")
	public @ResponseBody ListResponse<Fabric> getList(Args args,int pageindex, int pagesize) throws Exception {
		
		//PageHelper.startPage(pageindex, pagesize);
		//List<User> list=userService.selectAll();
		
		Fabric fabric=new Fabric();
		fabric.setCollected(0);
		List<Fabric> list=fabricService.selectAll(fabric);
		
		logger.info("查看日志:"+fabric);
		System.out.println("------------------");
		logger.debug(fabric);
		//PageInfo<Fabric> page = new PageInfo<Fabric>(list);
		
		return FastResponse._().list(list);
	}
	
	@RequestMapping("/test33")
	public @ResponseBody ObjResponse<Fabric> getById() throws Exception {
		
		Fabric fabric=fabricService.selectById(2);
		
		return FastResponse._().obj(fabric);
	}	
/*	@RequestMapping("/test3")
	public @ResponseBody String getUserList() throws Exception {
		
		return "nihao";
	}	*/	
	

	//注册请求，页面跳转到register.jsp
	@RequestMapping("register")
	public ModelAndView register(){
		ModelAndView modelAndView = new ModelAndView();
		
		//通过字典类型查询角色对应的code
		DictionaryType dictionaryType = dictionaryTypeService.selectByName("系统角色");
		
		if(dictionaryType != null){
			//通过code获得Dictionary里面的value
			String type_code = dictionaryType.getCode();
			//将type_code添加到model中，方便在发起请求的时候有两个字段可以确定在字典中的值
			modelAndView.addObject("type_code", type_code);
			List<Dictionary> dictionaryList = dictionaryService.selectByType_code(type_code);
			if(dictionaryList != null){
				//将Dictionary中的code与value加到map中,在register.jsp页面中可以获得数据库中角色的类型
				Map<Integer, String> rolesMap = new HashMap<>();
				for(int temp = 0;temp < dictionaryList.size();temp++){
					
					rolesMap.put(temp, dictionaryList.get(temp).getValue());
					
				}
				modelAndView.addObject("rolesMap", rolesMap);
				modelAndView.setViewName("test/registerTest");
			}else{
				//遇到未知错误，跳转到error.jsp页面
				modelAndView.addObject("errorMsg", "未知错误，请稍后重试！");
				modelAndView.setViewName("error");
			}
		}else{
			//遇到未知错误，跳转到error.jsp页面
			modelAndView.addObject("errorMsg", "未知错误，请稍后重试！");
			modelAndView.setViewName("error");
		}
		
		return modelAndView;
	
	}

	// 用户提交角色
		@RequestMapping("roleSubmit")
		public ModelAndView roleSubmit(@RequestParam(value = "code", required = true) int code, Dictionary dictionary) {

			String role_type = null;
			String viewName = null;
			ModelAndView modelAndView = new ModelAndView();

			// 因为上一步在加到map中是从0开始，所以这里code+1
			code += 1;
			dictionary.setCode(code + "");
			dictionary = dictionaryService.selectByType_codeAndCode(dictionary);
			List<Dictionary> dictionaryList = null;
			if (dictionary != null) {
				role_type = dictionary.getValue();
				switch (role_type) {
				case "设计师":
					viewName = "test/designerRegister";
					dictionaryList = dictionaryService.selectByDicTypeName("设计师标签");
					break;
				case "普通用户":
					viewName = "commonRegister";
					dictionaryList = dictionaryService.selectByDicTypeName("普通用户标签");
					break;
				case "供应商":
					viewName = "providerRegister";
					dictionaryList = dictionaryService.selectByDicTypeName("供应商标签");
					break;
				case "企业":
					viewName = "enterpriseRegister";
					dictionaryList = dictionaryService.selectByDicTypeName("企业标签");
					break;
				default:
					viewName = "error";
					break;
				}
				if (viewName != "error") {

					if (dictionaryList != null) {
						// 将字典数据中跟所选角色相关的标签以map的形式加到model
						Map<String, String> labelMap = new HashMap<>();
						for (int temp = 0; temp < dictionaryList.size(); temp++) {
							labelMap.put(dictionaryList.get(temp).getCode(), dictionaryList.get(temp).getValue());
						}
						modelAndView.addObject("labelMap", labelMap);
					} else {
						viewName = "error";
					}
				} else {
					viewName = "error";
				}

			} else {
				viewName = "error";
			}
			modelAndView.setViewName(viewName);
			return modelAndView;
		}
		//用户提交注册数据,对每个角色都有的数据先录入角色表
		@RequestMapping("registerSubmit")
		public String registerSubmit(User user){
			//用户基础数据的非空验证与密码加密，所有用户都必须进行验证
			String username = user.getUsername();
			String password = user.getPassword();
			if(username != null && username != ""
			&& password != null && password != ""){
				user.setReg_datetime(new java.util.Date());
				user.setStatus(1);
				//对密码进行BCrypt加密
				BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
				user.setPassword(passwordEncoder.encode(password));
				String role = user.getRole();
				userService.insert(user);
				String forwardPath = null;
				
				//判断请求转发路径
			switch (role) {
				case "设计师":
					forwardPath = "designerSubmit.do?id=";
					break;
				case "普通用户":
					forwardPath = "commonSubmit.do?id=";
					break;
				case "供应商":
					forwardPath = "providerSubmit.do?id=";
					break;
				case "企业":
					forwardPath = "enterprise.do?id=";
					break;
				default:
					break;
				}
				//将id加到请求中，并将请求转发给designerSubmit
				return "forward:"+forwardPath+user.getId();
			}
			return "error";
		}
		
		//前端ajax请求时，看看数据库里面有没有该用户名
		@RequestMapping("verifyUsername")
		public @ResponseBody String verifyUsername(@RequestParam(value = "username",required = true) String username,
				Model model){
			System.out.println(username);
			User user = userService.selectByName(username);
			if(user == null){
				return "success";
			}
			return "fail";
		}
		
		@RequestMapping("designerSubmit")
		public String designerSubmit(User user,int[] label_code){
			
			
			return "test/search";
			
		}
		
		/*
		 * 
		 * 用于测试redis，没装redis的别试
		 * 
        */
		@RequestMapping("test4")
		public ModelAndView test4( String username,String password) throws Exception {		
						
			
			/*	      //连接本地的 Redis 服务
	      Jedis jedis = new Jedis("localhost");
	      System.out.println("Connection to server sucessfully");
	      
	      jedis.zadd("score",80.0,"a");
	      jedis.zadd("score",65.0,"b");
	      jedis.zadd("score",92.0,"c");
	      jedis.zadd("score",17.0,"d");
	      jedis.zadd("score",55.0,"e");
	      jedis.zadd("score",43.0,"f");

	      
	      Set set=jedis.zrevrange("score", 0, -1);
	      Iterator it=set.iterator();
	      while(it.hasNext()){
	    	  String name=it.next().toString();
	    	  System.out.println(name+"---"+jedis.zscore("score",name)+"---"+(jedis.zrevrank("score", name)+1));
	      }*/
			
		      Jedis  jedis = new Jedis("localhost");
		      System.out.println("Connection to server sucessfully");
		      
		      
		    List<User> list=null;
			
			Set<String> set=jedis.smembers("name"); 
			
			if(set.size()!=0){
				Iterator<String>  it=set.iterator();
				
				while(it.hasNext()){
					System.out.println(it.next());
				}				
			}
			else{			
				list=userService.selectAll();
				for(int i=0;i<list.size();i++){
					jedis.sadd("name", list.get(i).getUsername());		
				}
				//设置过期时间
				jedis.expire("name",5);
				for(int i=0;i<list.size();i++){
					System.out.println(list.get(i).getUsername()+"---");
				}
			}

					
			ModelAndView mav = new ModelAndView("index");
			mav.addObject("list", list);
			
			return mav;
		}		
		
}
